# -*- coding:utf-8 -*-
'''
# Author: xiguan
# Mail: xiguan.teng@qq.com
# -----
# Last Modified: 2022-05-11 16:28:52
# Modified By: xiguan
# -----
# Copyright (c) 2022 XiGuan Inc.
# 
# No Bug No error No warning.
# -----
'''
import json
from pickle import dump, dumps, loads

from flask import Blueprint, jsonify, request, session

from config import db_session, engine
from entity.Ignore import Ignore
# from enti.ignore import Ignore


ignore = Blueprint('ignore',__name__)

# 将忽略列表对象转化为 json 格式
def ignore_2_json(obj):
   return {
      "id": obj.id,
      "type": obj.type,
      "ignore": obj.ignore,
      "name": obj.name,
      "desc": obj.desc,
      "uid": obj.uid
   }

@ignore.route('/get_all/')
def get_all():
   user = loads(session.get("user"))
   ignores = list(db_session.query(Ignore).filter_by(uid = user.id).order_by("name"))
   db_session.close()
   return json.dumps(ignores, default=ignore_2_json)

# 添加忽略列表
@ignore.route('/add_ignore/')
def add_ignore():
   name = request.args.get("name")
   user = loads(session.get("user"))
   add_ignore = Ignore(type=0, name=name, ignore=1, desc="", uid=user.id)
   db_session.add(add_ignore)
   db_session.commit()
   return "OK"

# 保存忽略列表
@ignore.route('/save_ignore/')
def save_ignore():
   ignores = json.loads(request.args.get('ignores'))
   user = loads(session.get("user"))
   with engine.connect() as con:
      for item in ignores:
         item_id = item
         item_ignore = ignores[item]
         execute_string = "update ftp_server.ignore set `ignore` =" + str(item_ignore) + " where id = " + str(item_id) + " and uid = " + str(user.id)
         con.execute(execute_string)
   return "OK"